#!/bin/bash
# Author: hulu 
# QQ: 563293401
# aws cli ec2 session manager

# 1. aws ec2 能使用Session Manager管理
# 2. 控制端安装aws cli, aws ali Session Manager plugin，并能正常连接到aws获取信息, AWS用户需能拥有session manager权限，也可以使用根用户key(不建议)
# 3. aws ec2 有变化需先update list

Ec2_Tags=$1
Ec2_List="/tmp/aws-ec2.list"
Aws_Cli="/usr/local/bin/aws"
if [[ ! -f $Ec2_List ]]; then
    touch $Ec2_List
    chmod 777 $Ec2_List
fi

if [[ ! -z $Ec2_Tags ]]; then
    Ec2_Id=$(grep -w $Ec2_Tags $Ec2_List |awk '{print $1}')
fi

service_usage () {
    echo $"Usage: $0 tags|listupdate"
    echo "..................Tags List......................"
    cat $Ec2_List
    exit 2
}

tags_check () {
    e_tags=$(grep -w $Ec2_Tags $Ec2_List)
    if [[ -z $e_tags ]] || [[ -z $Ec2_Tags ]]; then
        echo "Please input EC2 TAGS"
        service_usage
        exit 2
    fi
}

ec2_list_update () {
    $Aws_Cli ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId, State.Name, Tags[0].Value]' --output text >$Ec2_List
    cat $Ec2_List
    echo "Ec2 list update done......"
    exit 0
}

ec2_con () {
    $Aws_Cli ssm start-session --target $Ec2_Id
}

case "$1" in
    listupdate )
        [ $# -ne 1 ] && { service_usage; exit; }
        ec2_list_update
        ;;
    
    $Ec2_Tags )
        [ $# -ne 1 ] && { service_usage; exit; }
        tags_check
        ec2_con
        ;;
    
    * )
        service_usage
        ;;
esac
exit 0